/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import {
  defineComponent,
  InjectionKey,
  KeepAlive,
  onBeforeMount,
  onMounted,
  provide,
  ref
} from 'vue'
import { useI18n } from 'vue-i18n'
import TreeData from './components/tree-data'
import DefaultPage from './components/default-page'
import TabsMenu from './components/tabs-menu'
import { useTreeData } from './components/use-tree-data'
import styles from './index.module.scss'
import { useTabsRouteStore } from '@/store/sqlconsole/tabs-route'
import { useSqlExecTabStore } from '@/store/sqlconsole/sql-exec-tab'
import { TimerQueue } from './components/timer-queue'

export const SqlConsoleSymbol: InjectionKey<any> = Symbol()
export const TabSymbol: InjectionKey<any> = Symbol()

const SqlConsole = defineComponent({
  name: 'SqlConsole',
  setup() {
    const timerSet = new TimerQueue({})
    provide(SqlConsoleSymbol, timerSet)

    const { t } = useI18n()
    const { variables, refresh, onHandleLoad } = useTreeData()
    const $$tabsRouteStore = useTabsRouteStore()
    const $sqlExecTabStore = useSqlExecTabStore()

    const dbIds = ref<string[]>([])

    onBeforeMount(() => {
      // initial clear all state
      $$tabsRouteStore.clearRoute
      $sqlExecTabStore.clearTab
      // clear timer
      timerSet.clearAllTimer()
    })

    onMounted(() => {
      dbIds.value = $$tabsRouteStore.getDbIds || []
      refresh()
    })

    return {
      t,
      dbIds,
      variables,
      refresh,
      onHandleLoad
    }
  },
  render() {
    return (
      <div class={styles.container}>
        <TreeData
          tree={this.variables.tree}
          loading={this.variables.treeLoading}
          onLoad={this.onHandleLoad}
          refresh={this.refresh}
        />
        {this.dbIds.length === 0 ? (
          <DefaultPage
            treeLen={this.variables.tree.length}
            dbIdsLen={this.dbIds.length}
          />
        ) : (
          <div class={styles.contentBox}>
            <TabsMenu />
            <div class={styles.routerSlot}>
              {/* <transition name='move' mode='out-in'> */}
              <KeepAlive>
                <router-view
                  name='sql-console-tab'
                  key='sql-console-tab'
                ></router-view>
              </KeepAlive>
              {/* </transition> */}
            </div>
          </div>
        )}
      </div>
    )
  }
})

export default SqlConsole
